package backpage.controller;

import backpage.common.Result;
import backpage.dto.EmployeeLevelAdjustmentDTO;
import backpage.dto.LevelAdjustmentDTO;
import backpage.dto.LevelAdjustmentQueryDTO;
import backpage.dto.LevelAdjustmentRecordDTO;
import backpage.service.LevelAdjustmentService;
import lombok.RequiredArgsConstructor;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.List;

@RestController
@RequestMapping("/api/level-adjustment")
@RequiredArgsConstructor
public class LevelAdjustmentController {

    private final LevelAdjustmentService levelAdjustmentService;

    // Add this new endpoint
    @GetMapping("/all-employees")
    public Result<List<EmployeeLevelAdjustmentDTO>> getAllEmployees() {
        List<EmployeeLevelAdjustmentDTO> employees = levelAdjustmentService.getAllEmployees();
        return Result.success(employees);
    }

    @GetMapping("/employees")
    public Result<List<EmployeeLevelAdjustmentDTO>> getAdjustableEmployees(
            @RequestParam(required = false) Integer role,
            @RequestParam(required = false) Integer departmentId,
            @RequestHeader("X-User-Id") Integer currentUserId,
            @RequestHeader("X-User-Role") Integer currentUserRole) {

        List<EmployeeLevelAdjustmentDTO> employees = levelAdjustmentService
                .getAdjustableEmployees(currentUserId, currentUserRole, departmentId);
        return Result.success(employees);
    }

    @PostMapping("/adjust")
    public Result<Void> adjustSalaryLevel(@RequestBody LevelAdjustmentDTO adjustmentDTO,
                                          @RequestHeader("X-User-Id") Integer operatorId,
                                          @RequestHeader("X-User-Role") Integer operatorRole) {

        levelAdjustmentService.adjustSalaryLevel(adjustmentDTO, operatorId, operatorRole);
        return Result.success();
    }

    @GetMapping("/records")
    public Result<List<LevelAdjustmentRecordDTO>> getAdjustmentRecords(
            @RequestParam @DateTimeFormat(pattern = "yyyy-MM-dd") Date startDate,
            @RequestParam @DateTimeFormat(pattern = "yyyy-MM-dd") Date endDate,
            @RequestParam(required = false) Integer employeeId) {

        LevelAdjustmentQueryDTO queryDTO = new LevelAdjustmentQueryDTO();
        queryDTO.setStartDate(startDate);
        queryDTO.setEndDate(endDate);
        queryDTO.setEmployeeId(employeeId);

        List<LevelAdjustmentRecordDTO> records = levelAdjustmentService.getAdjustmentRecords(queryDTO);
        return Result.success(records);
    }
}